package network;

import java.io.*;
import java.util.*;
import java.net.*;
import network.*;
import network.state.*;

public class ClientConn
{
    private Socket mainConn;
    private Socket backupConn;
    private BufferedReader myInputM, myInputB;
    private BufferedWriter myOutputM, myOutputB;
    ConnState mainState, backupState,myState;

    public ClientConn()
    {
    }

    public boolean connectServer(String ip1,String ip2)
    {
        try
        {
            mainState = ConnState.ONLINE;
            mainConn = new Socket(ip1,1337);
        }
        catch (Exception e)
        {
            System.out.println(e);
            myState = ConnState.MAIN_DOWN;
            mainState = ConnState.OFFLINE;
        }

        try
        {
            backupState = ConnState.ONLINE;
            backupConn = new Socket(ip2,1337);
        }
        catch (Exception e)
        {
            System.out.println(e);
            backupState = ConnState.OFFLINE;
            myState = ConnState.BACKUP_DOWN;

            if (mainState==ConnState.OFFLINE)
            {
                myState = ConnState.BOTH_DOWN;
                return false;
            }

        }
        
        try
        {
            myInputM = new BufferedReader(new InputStreamReader(mainConn.getInputStream()));
            myInputB = new BufferedReader(new InputStreamReader(backupConn.getInputStream()));
            myOutputM = new BufferedWriter(new OutputStreamWriter(mainConn.getOutputStream()));
            myOutputB = new BufferedWriter(new OutputStreamWriter(backupConn.getOutputStream()));
        }
        catch (Exception e)
        {
            System.out.println(e);
            return false;
        }

        return true;
    }
    
    public boolean sendMsg(String myString)
    {
        boolean state;

        if (Network.sendMsg(myString,myOutputM));
        return Network.sendMsg(myString,myOutputM);
    }

    public String recvMsg()
    {
        return recvMsg();
    }

    public boolean setConnState(int type, ConnState myState)
    {
        switch (type)
        {
            case 1:
            mainState = myState;
            break;
            case 2:
            backupState = myState;
            break;
            default:
        }
        updateConnState();
        return true;
    }
    
    private boolean updateConnState()
    {
        if (mainState == ConnState.OFFLINE)
        {
            if (backupState == ConnState.OFFLINE)
                myState = ConnState.BOTH_DOWN;
            else
                myState = ConnState.MAIN_DOWN;
        }
        else if (backupState==ConnState.OFFLINE)
        {
            myState = ConnState.BACKUP_DOWN;
        }
        else
        {
            myState = ConnState.BOTH_UP;
        }

        return true;
    }

    public ConnState getConnState()
    {
        return myState;
    }


}
